import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getLoginApi } from '@/apis/login'
import { type user } from '@/apis/model/loginModel'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
export const useUserStore = defineStore(
  'user',
  () => {
    const router = useRouter()
    const user = ref<user>()
    const login = async (username: string, password: string) => {
      const res = await getLoginApi({ username, password })
      user.value = res.result
      if (res.status === 200) {
        ElMessage({
          showClose: true,
          message: res.message,
          type: 'success'
        })
        router.push({
          path: '/index'
        })
      } else if (res.status === 202) {
        ElMessage({
          showClose: true,
          message: res.message,
          type: 'warning'
        })
      } else
        ElMessage({
          showClose: true,
          message: res.message,
          type: 'warning'
        })
    }
    const clearUser = () => {
      sessionStorage.clear()
    }

    return { user, login, clearUser }
  },
  {
    // 使用该插件，开启数据缓存
    persist: {
      key: 'user',
      paths: ['user'],
      storage: sessionStorage
    }
  }
)
